package com.apache.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.apache.api.api.ApiService;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;

import net.sf.json.JSONObject;

/**
 * description:
 *
 * @author dyh 创建时间：2018年06月24日
 */
public abstract class ServiceActionSuper {

	protected abstract ApiService getApiService(String beanId);

	/**
	 * 获取接口执行结果
	 */
	protected abstract String getResultEntityMsg(ResultEntity entity, String paramType);

	protected abstract ParamsVo getXMLMapParse(String paramStr, Map<String, Object> headMap);

	/**
	 * description:  接口统一调用方法
	 */
	@RequestMapping(value = "doService.action", method = RequestMethod.GET)
	public void doService(HttpServletRequest request, HttpServletResponse response) {
		try {
			restfulRequest(request, response);
		} catch (Exception e) {
		}
	}

	/**
	 * description:  系统统一接口(restfull--post)
	 */
	@RequestMapping(value = "/doService", method = RequestMethod.POST)
	public void doServiceForPost(HttpServletRequest request, HttpServletResponse response) {
		restfulRequest(request, response);
	}

	/**
	 * description:  系统统一接口(restfull--get)
	 */
	@RequestMapping(value = "/doService", method = RequestMethod.GET)
	public void serviceForGet(HttpServletRequest request, HttpServletResponse response) {
		restfulRequest(request, response);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void restfulRequest(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String sysPass = request.getParameter("sysPass");
		String beanId = "";
		String reqMsg = null;
		try {
			reqMsg = IOUtils.toString(request.getInputStream(), "UTF-8");//以流的方式传参
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (Validator.isNull(reqMsg)) {//xml参数
			String paramStr = request.getParameter("params");
			if (Validator.isNotNull(paramStr)) {
				Map<String, Object> headMap = new HashMap<String, Object>();
				vo = getXMLMapParse(paramStr, headMap);
				vo.setMethodKey(headMap.get("MethodCode").toString());
				sysPass = Validator.getDefaultStr(sysPass, String.valueOf(vo.getParams("sysPass")));
				beanId = String.valueOf(headMap.get("BeanId"));
			} else {
				try {
					String methodCode = request.getParameter("MethodCode");
					if (StrUtil.isNull(methodCode)) {
						String streamStr = IOUtils.toString(request.getInputStream(), "UTF-8");
						if (StrUtil.isNotNull(streamStr)) {
							Map<String, Object> headMap = new HashMap<String, Object>();
							vo = getXMLMapParse(streamStr, headMap);
							vo.setMethodKey(headMap.get("MethodCode").toString());
							sysPass = Validator.getDefaultStr(sysPass, String.valueOf(vo.getParams("sysPass")));
							beanId = String.valueOf(headMap.get("BeanId"));
						}
					} else {
						Map<String, Object> bodyMap = getRequestParam(request);
						vo.setMethodKey(methodCode);
						vo.setParams(bodyMap);
						beanId = request.getParameter("BeanId");
					}
				} catch (IOException e) {
				}
			}
		}else{
			Map<String, Object> headMap = new HashMap<String, Object>();
			vo = getXMLMapParse(reqMsg, headMap);
			vo.setMethodKey(headMap.get("MethodCode").toString());
			sysPass = String.valueOf(vo.getParams("sysPass"));
			beanId = String.valueOf(headMap.get("BeanId"));
		}
		getResultInfo(vo, sysPass, request, response, beanId);
	}

	/**
	 * 获取接口执行结果
	 */
	private void getResultInfo(ParamsVo vo, String sysPass, HttpServletRequest request, HttpServletResponse response,
			String beanId) {
		String result = "";
		try {
			ResultEntity entity = null;
			if (isAllow(sysPass)) {//合法身份验证
				ApiService service = getApiService(beanId);
				entity = service.doService(vo);
				if (Validator.isEmpty(entity)) {
					entity = new ResultEntity();
					entity.setResult("false");
					entity.setMessage("接口调用失败！");
				}
			} else {
				entity = new ResultEntity();
				entity.setResult("false");
				entity.setMessage("没有访问权限");
			}
			String callback = request.getParameter("callback");
			PrintWriter out = response.getWriter();
			if (Validator.isNull(callback)) {
				String paramType = request.getParameter("ParamType");
				result = getResultEntityMsg(entity, paramType);
				response.setContentType("text/html; charset=UTF-8");
				out.print(result);
			} else {///支持jsonp数据格式
				response.setContentType("application/javascript");
				if (Validator.isEmpty(entity.getEntity())) {
					ResultMsg msg = new ResultMsg("F", "操作失败");
					JSONObject json = JSONObject.fromObject(msg);
					result = json.toString();
				} else {
					JSONObject json = JSONObject.fromObject(entity);
					result = json.toString();
				}
				out.print(callback + "(" + result + ")");
			}
			out.flush();
		} catch (Exception e) {
		}
	}

	/**
	 * 获取请求参数
	 */
	private Map<String, Object> getRequestParam(HttpServletRequest request) {
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		Set keSet = request.getParameterMap().entrySet();
		try {
			for (Iterator itr = keSet.iterator(); itr.hasNext();) {
				Map.Entry me = (Map.Entry) itr.next();
				String ok = String.valueOf(me.getKey());
				if ("ParamType".equals(ok) || "callback".equals(ok) || "MethodCode".equals(ok) || "BeanId".equals(ok))
					continue;
				Object ov = me.getValue();
				String value = "";
				if ((ov instanceof String[])) {
					String[] vls = (String[]) ov;
					value = vls[0];
				} else {
					value = String.valueOf(ov);
				}
				if (StrUtil.isNotNull(value)) {
					if (value.equals(new String(value.getBytes("iso8859-1"), "iso8859-1"))) {
						value = new String(value.getBytes("iso8859-1"), "UTF-8");
					}
					bodyMap.put(ok, value);
				}
			}
		} catch (Exception e) {
		}
		return bodyMap;
	}

	/**
	 * 对外接口访问合法用户校验
	 *
	 * @param sysPass 校验码
	 * @return
	 */
	private boolean isAllow(String sysPass) {
		String pushPass = ConfigUtil.getInstance().interfacePass();
		if (StrUtil.isNull(pushPass)) {//如果服务端不设置密码
			return true;
		} else {
			return pushPass.equals(sysPass);
		}
	}
}
